package com.lyf.boot.config;

import com.lyf.boot.handler.TioServerHandler;
import com.lyf.boot.listener.TioServerIpStatListener;
import com.lyf.boot.listener.TioServerListener;
import com.lyf.boot.properties.TioWebSocketProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.tio.server.TioServerConfig;
import org.tio.websocket.server.WsServerStarter;

import java.io.IOException;

/**
 * @author Luyufan
 * @date 2025/1/14
 **/
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "tio.websocket.server", name = "enabled", havingValue = "true")
public class WebSocketConfig {

    private final TioWebSocketProperties tioWebSocketProperties;

    private final TioServerHandler tioServerHandler;

    private final TioServerListener tioServerListener;

    private final TioServerIpStatListener tioServerIpStatListener;

    @Bean
    public WsServerStarter wsServerStarter() throws IOException {
        // 设置处理器
        WsServerStarter wsServerStarter = new WsServerStarter(tioWebSocketProperties.getPort(), tioServerHandler);
        // 获取到ServerTioConfig
        TioServerConfig serverTioConfig = wsServerStarter.getTioServerConfig();
        // 设置心跳超时时间，默认：1000 * 120
        serverTioConfig.setHeartbeatTimeout(tioWebSocketProperties.getHeartbeatTimeout());

        serverTioConfig.setTioServerListener(tioServerListener);

        serverTioConfig.setName(tioWebSocketProperties.getProtocolName());

        serverTioConfig.ipStats.addDuration(tioWebSocketProperties.getIpStatDuration());

        serverTioConfig.setIpStatListener(tioServerIpStatListener);

        // 启动
        wsServerStarter.start();
        return wsServerStarter;
    }
}
